package com.caiyouxi.pay.payment.alipay;


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.caiyouxi.common.util.Log;
import com.caiyouxi.goods.model.GoodsInfo;
import com.caiyouxi.order.model.OrderBean;
import com.caiyouxi.pay.model.PaymentBean;
import com.caiyouxi.pay.model.PaymentConfigBean;
import com.caiyouxi.pay.service.PayBaseService;
import com.caiyouxi.pay.service.PayLogUtil;
import com.caiyouxi.pay.service.PayServiceImpl;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


/**
 * 支付宝支付相关
 */

@Service
public class AlipayPayService implements PayBaseService
{
	private Logger logger = Logger.getLogger(PayServiceImpl.class);

	@Override
	public JSONObject get_third_pay_resp(PayServiceImpl payService, OrderBean bean, GoodsInfo gInfo, PaymentConfigBean ppb)  throws Exception{

		logger.info("发起支付宝支付...");
		//发送状态
		String send_status="SUCCESS";
		//发送后交易状态
		String send_trade_status="SUCCESS";
		String error_code="";
		String error_msg="";
		String raw="";
		String result_raw="";

		//获取第三方配置信息
		JSONObject thirid_config = JSONObject.parseObject(ppb.getParam_config());
		String body= bean.getTitle();//商品描述
		String pay_url = thirid_config.getString("pay_url");//请求的接口URL
		String app_id = thirid_config.getString("app_id");//应用ID
		String public_key = thirid_config.getString("public_key");//支付宝公钥
		String private_key = thirid_config.getString("private_key");//商户私钥
		String sign_type = thirid_config.getString("sign_type");//终端IP
		String notify_url = thirid_config.getString("notify_url");//终端IP
		String input_charset = thirid_config.getString("input_charset");//终端IP
		int is_support_cred = ppb.getIs_support_creditcard();//是否要以使用信用卡
		double order_money = bean.getTotal_amount();
		BigDecimal bd = new BigDecimal(order_money/100);
		BigDecimal total_money = bd.setScale(2, bd.ROUND_DOWN);
		logger.info("支付宝订单金额:"+total_money);

		// 实例化客户端
		System.out.println("===================app_id="+app_id);
		System.out.println("===================private_key="+private_key);
		System.out.println("===================public_key="+public_key);
		System.out.println("===================sign_type="+sign_type);
		System.out.println("===================input_charset="+input_charset);
		System.out.println("===================pay_url="+pay_url);
		AlipayClient alipayClient = new DefaultAlipayClient(pay_url, app_id,private_key, "json", input_charset, public_key, sign_type);
		// 实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
		AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
		// SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
		AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
		model.setBody(bean.getTitle());
		model.setSubject(bean.getTitle());
		model.setOutTradeNo(bean.getId());
		model.setTimeoutExpress("30m");
		model.setTotalAmount(String.valueOf(total_money));

		raw = JSONObject.toJSONString(model);

		if(0==is_support_cred)
		{
			//不支持信用卡
			model.setDisablePayChannels("credit_group");
		}
		request.setBizModel(model);
		request.setNotifyUrl(notify_url);
		String return_str="";
		try
		{
			// 这里和普通的接口调用不同，使用的是sdkExecute
			AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
			return_str = response.getBody();										// 可以直接给客户端请求，无需再做处理。
			result_raw = return_str;
		} catch (AlipayApiException e)
		{
			send_status="FAILD";
			send_trade_status="FAILD";
			e.printStackTrace();
		}


		//增加支付请求和通知日志
		Log.e("payService" + payService.toString());
		PayLogUtil.insert(payService,"ALIPAY","",bean.getBuyer_user_id() == null ? "" : bean.getBuyer_user_id().toString(),bean.getBuyer_user_id() == null ? "" : bean.getBuyer_user_id().toString(),
				"PAY","SEND",bean,gInfo,200,send_status,send_trade_status,raw,result_raw,
				pay_url,error_code,error_msg);
//		try {
//			Log.e("增加支付请求和通知日志 开始");
//			PaymentLogBean plb = PayLogUtil.insertBean("ALIPAY","","","",
//				"PAY","SEND",bean,200,send_status,send_trade_status,raw,result_raw,
//				pay_url,error_code,error_msg);
//			payService.add_payment_log(plb);
//			Log.e("增加支付请求和通知日志 结束");
//		} catch (Exception e) {
//			e.printStackTrace();
//		    Log.e("增加支付请求和通知日志 异常");
//		}

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("alipay_resp", return_str);
        System.out.println("返回给APP:"+jsonObject.toString());
		return jsonObject;
	}

	/**
	 * 支付宝回调
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> get_pay_result(PayServiceImpl payService,HttpServletRequest request, HttpServletResponse response) throws Exception {


		Log.d("处理支付宝异步回调开始....");
		//发送状态
		String send_status="SUCCESS";
		//发送后交易状态
		String send_trade_status="SUCCESS";
		String error_code="";
		String error_msg="";
		String raw="";
		String result_raw="";

		Map<String,Object> map = new HashMap<String,Object>();
		String return_code="SUCCESS";
		String order_id ="";
		// 获取支付宝POST过来反馈信息
		Map<String, String> params = new HashMap<String, String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();)
		{
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++)
			{
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		// 切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
		// 切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
		// boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String
		// publicKey, String charset, String sign_type)
		try
		{
			PaymentBean pb = payService.get_payment_by_provider("ALIPAY");
			JSONObject thirid_config = JSONObject.parseObject(pb.getParam_config());
			String alipay_public_key = thirid_config.getString("public_key");//支付宝公钥
			String input_charset = thirid_config.getString("input_charset");//
			String sign_type = thirid_config.getString("sign_type");//
			boolean flag = AlipaySignature.rsaCheckV1(params,alipay_public_key, input_charset,sign_type);
			if (flag)
			{
				if ("TRADE_SUCCESS".equals(params.get("trade_status")))
				{
					// 付款金额
					String amount = params.get("buyer_pay_amount");
					// 商户订单号
					String out_trade_no = params.get("out_trade_no");
					// 支付宝交易号
					String trade_no = params.get("trade_no");
					map.put("order_id",out_trade_no);

					Log.d("处理支付宝异步回调....");
				}
				else {
					return_code = "FAILD";
				}
			}
		} catch (AlipayApiException e)
		{
			e.printStackTrace();
			return_code = "FAILD";
		}

		//增加支付请求和通知日志
//		PayLogUtil.insert(payService,"ALIPAY","","","",
//				"PAY","RECEIVE",bean,200,send_status,send_trade_status,requestParams.toString(),return_code,
//				"",error_code,error_msg);

		map.put("return_code",return_code);
		Log.d("处理支付宝异步结束：....:"+return_code);
		return map;
	}


}
